<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="inputChange"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportStaffExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              <span>{{ row.formOfEmployment===1?'正式':'非正式' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{row}">
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="btnAllotRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除该员工吗？"
                @onConfirm="comfirmDel(row.id)"
              >
                <el-button slot="reference" type="text" style="margin-left:10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" align="middle" justify="end" style="height:60px">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="getEmployeeList"
    />
    <el-dialog title="分配角色" :visible.sync="showDialog">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in allotList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="5">
          <el-button size="small" type="primary" @click="btnSureAssign">确定</el-button>
          <el-button size="small" style="margin-right:24px;" @click="showDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { _getDepartmentList } from '@/api/department'
import { tranListToTreeData } from '@/utils'
import { _assignEmployee, _deleteEmployee, _exportStaffExcel, _getAllotList, _getEmployeeBasic, _getEmployeeList } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/ImportExcel'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [], // 组织数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 存储查找查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      total: 0,
      employeeList: [],
      showExcelDialog: false,
      showDialog: false,
      allotList: [],
      roleIds: [],
      currentId: null
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      this.depts = tranListToTreeData(await _getDepartmentList(), 0)
      // 一开始刚进页面时记录节点
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(() => {
        // 记录传智教育节点后设置为选中状态
        // 等树组件渲染完毕再设置
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      // 默认选中传智教育并获取员工列表
      this.getEmployeeList()
    },
    selectNode(node) {
      // node回调参数为当前对象数据
      // console.log(node)
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await _getEmployeeList(this.queryParams)
      this.employeeList = rows
      this.total = total
    },
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployeeList()
    },
    inputChange() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    async exportStaffExcel() {
      const res = await _exportStaffExcel()
      // console.log(res)
      // FileSaver.saveAs(result,'员工信息表.xlsx')
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    async comfirmDel(id) {
      await _deleteEmployee(id)
      if (this.employeeList.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    async btnAllotRole(id) {
      this.currentId = id
      this.allotList = await _getAllotList()
      const { roleIds } = await _getEmployeeBasic(this.currentId)
      this.roleIds = roleIds
      this.showDialog = true
    },
    async btnSureAssign() {
      this.roleIds = await _assignEmployee({ id: this.currentId, roleIds: this.roleIds })
      this.$message.success('角色分配成功')
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
